package com.aigc.sclassroom.utils;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.io.IOException;

public class chatWenXin {

    private static final String API_KEY = "piZcYig3SyDPLLGqaYM5oQXU";
    private static final String SECRET_KEY = "wb7bVlHcxG3Ar7C2SZgTQ4yYZu7BJQS5";

    public static String getAccessToken() throws IOException, InterruptedException {
        String url = "https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id=" + API_KEY + "&client_secret=" + SECRET_KEY;

        HttpClient client = HttpClient.newHttpClient();
        HttpRequest request = HttpRequest.newBuilder()
                .uri(URI.create(url))
                .build();

        HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
        JSONObject jsonResponse = JSONObject.parseObject(response.body());
        return jsonResponse.getString("access_token");
    }

    public static String doChat(String content) throws IOException, InterruptedException {
        String accessToken = getAccessToken();
        String chatUrl = "https://aip.baidubce.com/rpc/2.0/ai_custom/v1/wenxinworkshop/chat/ernie-3.5-128k-preview?access_token=" + accessToken;
        JSONObject payload = new JSONObject();
        JSONArray messages = new JSONArray();
        JSONObject message = new JSONObject();
        message.put("role", "user");
        message.put("content", content);
        messages.add(message); // 注意：fastjson使用add方法添加元素到JSONArray
        payload.put("messages", messages);
        payload.put("temperature", 1.0);
        payload.put("response_format", "json_object");

        HttpClient client = HttpClient.newHttpClient();
        HttpRequest request = HttpRequest.newBuilder()
                .uri(URI.create(chatUrl))
                .header("Content-Type", "application/json")
                .POST(HttpRequest.BodyPublishers.ofString(payload.toJSONString())) // 注意：使用toJSONString()方法
                .build();

        HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
        return response.body();
    }
}
